package com.example.detect.Activity

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import com.example.tools.CheckPermissionsUtils
import com.example.tools.Utils


/**
 * 无障碍服务，获取窗口的包名和class
 */
class DetectActivity : AccessibilityService() {
    private val TAG = "DetectActivity"
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate");
        //从系统设置里面开启辅助功能时回调1
    }

    /**
     * 中断可访问性反馈
     */
    override fun onInterrupt() {

    }

    lateinit var floatingView: FloatingView
    override fun onServiceConnected() {
        super.onServiceConnected()
        //从系统设置里面开启辅助功能时回调2
        val serviceInfo = AccessibilityServiceInfo()
        serviceInfo.eventTypes = AccessibilityEvent.TYPES_ALL_MASK
        serviceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
        serviceInfo.notificationTimeout = 100
        setServiceInfo(serviceInfo)
        if (CheckPermissionsUtils.ckeckPermissionPopWindow(applicationContext)) {
            initView()
        }
    }


    private fun initView() {
        floatingView = FloatingView(applicationContext)
        Utils.setWindowManagerAddView(floatingView, applicationContext)
    }


    /**
     * 发生用户界面事件回调此事件
     * @param event
     */
    @SuppressLint("SetTextI18n")
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        event?.let {
            if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                var className = event.className
                val packageName = event.packageName
                if (!TextUtils.isEmpty(className) &&
                    !TextUtils.isEmpty(packageName) &&
                    className.contains("com.")
                ) {
                    if (className.contains(packageName)) {
                        className = className.toString().replace(packageName.toString(), "")
                        className = className.replace("..", "");
                        if (className[0] == '.')
                            className = className.substring(1);
                    }
                    //设置文本
                    floatingView.mTvPackageName?.setText("包名$packageName\n类名$className");
                }
                //监听当前窗口变化，获取Package名和Class名
                Log.e("TAG", "shine:onAccessibilityEvent,className =" + className);
                Log.e("TAG", "shine:onAccessibilityEvent,packageName=" + packageName);
            }
        }

    }

}
